import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/test_function/sim_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'bean/sim_info_list_response_bean.dart';

class SimSettingsInfoPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SimSettingsInfoPage";

  final String content;
  final String type;

  const SimSettingsInfoPage({Key key, this.type, this.content,}):super(key: key);

  @override
  _SimSettingsInfoPageState createState() => _SimSettingsInfoPageState();

  ///跳转方法
  static Future<String> navigatorPush(BuildContext context, String type, String content) {
    return RouterUtils.routeForFutureResult(
      context,
      SimSettingsInfoPage(
        type: type,
        content: content,
      ),
      routeName: SimSettingsInfoPage.ROUTER,
    );
  }
}

class _SimSettingsInfoPageState extends BaseState<SimSettingsInfoPage>{

  TextEditingController _controller;
  bool isAlive = false;

  String _content;
  String _type;
  String _hint;

  List<String> _contentList;
  String _selectContent;
  SimViewModel _viewModel;
  String _title;

  @override
  void initState() {
    super.initState();
    _contentList = new List();
    _controller = TextEditingController();
    _content = widget?.content;
    _selectContent =  _content;
    _type = widget?.type??"00";
    isAlive = judgeAlive();
    if("00" == _type){
      _hint = "请输入运营商名称";
      _title = "运营商";
    }else if("01" == _type){
      _hint = "请输入代理商名称";
      _title = "代理商";
    }else{
      _hint = "请输入套餐规格";
      _title = "套餐规格";
    }
    _viewModel = new SimViewModel(this);
    _viewModel.getSimInfoList(context, _type);
  }

  bool judgeAlive(){
    return StringUtils.isNotEmpty(_selectContent);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: true,
      resizeToAvoidBottomInset: true,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toPlaceHolderWidget(),
    );
  }

  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getSimInfoList(context, _type),
            loadingOnClick: () => _viewModel
                .getSimInfoList(context, _type),
            child: child,
          );
        },
        child: _toInfoWidget());
  }

  Widget _toInfoWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.simInfoListValueNotifier,
      builder: (BuildContext context, SimInfoListDataBean listDataBean, Widget child){
        if(listDataBean != null && listDataBean.SIMInfoList != null && listDataBean.SIMInfoList.isNotEmpty){
          _contentList.clear();
          listDataBean.SIMInfoList.forEach((element) {
            if(StringUtils.isNotEmpty(element.content)){
              _contentList.add(element.content);
            }
          });
        }
        return Column(
          children: [
            _toTopBarWidget(),
            _toContentWidget(),
            SizedBox(height: 10,),
            _toListWidget(listDataBean?.SIMInfoList),
          ],
        );
      },
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      title: _title,
      isShowBack: true,
      rightWidget: _toSaveButton(),
    );
  }

  ///保存
  Widget _toSaveButton(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: isAlive,
      width: 48,
      height: 24,
      unSelectBgColor:
      ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 12),
      selectedTextStyle: TextStyle(
        color: Colors.white, fontSize: 12,),
      text: "保存",
      onTap: (){
        _save();
      },
    );
  }

  void _save(){
    if(_contentList.contains(_selectContent)){
      RouterUtils.pop(context, result: _selectContent);
    }else{
      _viewModel.addSimInfo(context, _selectContent, _type);
    }
  }

  ///输入框
  Widget _toContentWidget(){
    return Container(
      height: 50,
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: [
          Image.asset(
            'images/icon_add_company.png',
            width: 17,
          ),
          SizedBox(
            width: 10,
          ),
          Expanded(
            child: VgTextField(
              controller: _controller,
              maxLines: 1,
              cursorWidth: 2,
              autofocus: ((_contentList?.length??0) == 0),
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                border: InputBorder.none,
                counterText: "",
                hintText: _hint,
                hintStyle: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getHintGreenColor_5E687C(),
                    fontSize: 14
                ),
              ),
              style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance()
                      .getTextMainColor_D0E0F7()
              ),
              maxLimitLength: 10,
              onChanged: (String str) {
                _selectContent = str;
                isAlive = judgeAlive();
                setState(() {});
              },
            ),
          ),
          Visibility(
            visible: StringUtils.isNotEmpty(_controller?.text??""),
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                setState(() {
                  _controller?.text = "";
                });
              },
              child: Container(
                height: 50,
                width: 45,
                alignment: Alignment.center,
                child: Image.asset(
                  "images/icon_clear_content.png",
                  width: 15,
                  height: 15,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }



  ///列表
  Widget _toListWidget(List<SIMInfoListBean> list){
    return ListView.separated(
        padding: EdgeInsets.all(0),
        itemCount: list?.length??0,
        shrinkWrap: true,
        physics: BouncingScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return _toItemWidget(list[index]);
        },
        separatorBuilder: (BuildContext context, int index) {
          return _toFilterWidget();
        });
  }

  ///item
  Widget _toItemWidget(SIMInfoListBean item){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        _selectContent = item?.content??"";
        if(_contentList.contains(_selectContent)){
          RouterUtils.pop(context, result: _selectContent);
        }else{
          setState(() {
            _selectContent = item?.content??"";
            isAlive = judgeAlive();
          });
        }
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: Row(
          children: [
            SizedBox(width: 15,),
            Expanded(
              child: Text(
                item?.content,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 14,
                  color: (item?.content == _selectContent)?ThemeRepository.getInstance().getPrimaryColor_1890FF():ThemeRepository.getInstance().getTextColor_D0E0F7(),
                ),
              ),
            ),
            SizedBox(width: 5,),
            Spacer(),
            Visibility(
              visible: item?.content == _selectContent,
              child: Image.asset(
                "images/icon_selected.png",
                width: 11,
              ),
            ),
            SizedBox(width: 20,)
          ],
        ),
      ),
    );
  }

  ///分割线
  Widget _toFilterWidget(){
    return Container(
      height: 1,
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Container(
        height: 1,
        color: Color(0XFF303546),
        margin: EdgeInsets.only(left: 15),
      ),
    );
  }
}